#!/usr/bin/env python

'''
    After the sorting app has run, you can run this to generate the
    conflicts.txt file needed by the jury application.

    You'll have to move this script to the right place to read the files.
'''

import sys, os

def readFile(name):
    fp = open(name)
    for l in fp.readlines():
        args = l.split()
        if len(args) == 0 or args[0].startswith('#'):
            continue
        yield args

def loadRev():
    ''' Load reviewers '''
    revs = {}
    dups = {}
    for args in readFile('map-reviewers.txt'):
        name = args[-1]
        if dups.has_key(args[-1]):
            name = ' '.join(args[1:])
            if dups.has_key(name):
                print 'Duplicate reviewer', name
        revs[args[0]] = name
        dups[name] = True
    return revs

def loadSubmissions():
    ''' Load submissions '''
    subs = {}
    for args in readFile('map-submissions.txt'):
        subs[args[0]] = args[-1].replace('general_', '')
    return subs

def saveConflicts(fp, conflicts):
    lines = []
    for c in conflicts:
        conflicts[c].sort()
        last = None
        unique = []
        for u in conflicts[c]:
            if u != last:
                unique.append('%d' % u)
                last = u
        lines.append('%s: %s\n' % (c, ', '.join(unique)))
    lines.sort()
    fp.write(''.join(lines))

def main():
    revs = loadRev()
    subs = loadSubmissions()
    conflicts = {}
    for args in readFile('map-conflict.txt'):
        rev = revs[args[0]]
        sub = int(subs[args[1]])
        if not conflicts.has_key(rev):
            conflicts[rev] = []
        conflicts[rev].append(sub)
    for args in readFile('run/chair-conflict.txt'):
        # Yes, the order is swapped
        rev = revs[args[1]]
        sub = int(subs[args[0]])
        if not conflicts.has_key(rev):
            conflicts[rev] = []
        conflicts[rev].append(sub)
    saveConflicts(open('conflicts.txt', 'w'), conflicts)

if __name__ == '__main__':
    main()
